package com.bagus.mediapipefacedetection.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

public class IMediaPlayer {
    public MediaPlayer mMediaPlayer;
    private Context mContext;
    private boolean isComplete;

    public IMediaPlayer(Context mContext) {
        this.mContext = mContext;
        mMediaPlayer = new MediaPlayer();
    }

    public void close(){
        try {
            mContext = null;
            if (mMediaPlayer != null) {
                mMediaPlayer.reset();
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *重置 （重新设置播放器引擎）
     */
    public void reset(){
        try {
            if (mMediaPlayer != null) {
                mMediaPlayer.reset();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 多媒体播放
     */
    public void doPlay(int rawId) {
        if (this.mMediaPlayer == null || rawId <= 0)
            return;
        try {
            mMediaPlayer.reset();
            AssetFileDescriptor localAssetFileDescriptor = mContext.getResources().openRawResourceFd(rawId);
            mMediaPlayer.setDataSource(localAssetFileDescriptor.getFileDescriptor(),
                    localAssetFileDescriptor.getStartOffset(),
                    localAssetFileDescriptor.getLength());
            localAssetFileDescriptor.close();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                    isComplete = false;
                }
            });
            mMediaPlayer.prepareAsync();
        } catch (Exception localIOException) {
            localIOException.printStackTrace();
        }
    }

    public boolean isPlaying() {
        return (mMediaPlayer != null && mMediaPlayer.isPlaying());
    }

    public void setOnCompletionListener(final int rawId, boolean looping){
        if(mMediaPlayer == null){
            return;
        }
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                try {
                    isComplete = true;
                    doPlay(rawId);
                    if (mMediaPlayer == null){
                        return;
                    }
                    if (!looping) {
                        mMediaPlayer.setOnCompletionListener(null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public boolean isComplete() {
        return isComplete;
    }

    public void setComplete(boolean complete) {
        isComplete = complete;
    }

}